<?php
require_once 'oauth-library/OAuthServer.php';
require_once 'oauth-library/OAuthStore.php';

class Oauth extends MY_Controller
{
	private $db_conn = null;
	
	function Oauth()
	{
		parent::MY_Controller();
		
		# TODO: DATABASE parameters can be accessed from DB conf file
		include(APPPATH.'config/database'.EXT);
		//var_dump($db);die;
		
		# the oauth library requires basic mysql connection resource connection for db access;
		# the built in codeigniter wrapper is no good
		($this->db_conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password'])) 
			|| die(mysql_error());
		mysql_select_db($db['default']['database'], $this->db_conn) || die(mysql_error());
		
		mysql_query('SET NAMES utf8');
		
		OAuthStore::instance('MySQL', array('conn' => $this->db_conn));
		
		# this line is used to enable query string parameters to be passed to the controller
		parse_str($_SERVER['QUERY_STRING'], $_GET);
	}
	
	/**
	* 	Endpoint for getting OAuth request token
	*/
	public function request()
	{
		$server = new OAuthServer();
		$server->requestToken();
	}
	
	/**
	*	Display OAuth authorization page to the user where he shall be able to approve or decline
	*	the request of an external application to access his data
	*/
	public function authorize()
	{
		$this->lang->load('oauth');
		$this->lang->load('account');
		$this->load->library('form_validation');
		$viewdata = array();
		
		try
		{
			# verify if oauth_token is valid
			$oauth_token = $_REQUEST['oauth_token'];
			if(!preg_match('/^[a-z0-9]+$/i', $oauth_token))
				throw new Exception( lang('invalid_oauth_token') );

			# get consumer application title
			$store = OAuthStore::instance();
			$server = new OAuthServer();
			$token = $server->authorizeVerify();
			if(!$token)
				throw new Exception( lang('invalid_oauth_token') );					
			
			$viewdata['oauth_token'] = $oauth_token;
			$viewdata['consumer_title'] = $token['application_title'];
			
			$user_id = (int)$this->session->userdata('user_id');
			if(!$user_id)
			{				
				$viewdata['redirect_url'] = 'oauth/authorize?oauth_token=' . $oauth_token;
				$viewdata['nonce'] = md5(uniqid(rand(), false));
				$this->session->set_userdata('login_nonce', $viewdata['nonce']);
		
				if(isset($_GET['invalid']))
					$viewdata['login_message'] = lang('err_login');
				
				$this->data['header_data']['css'][] = '/css/home.css';
				$this->data['content'] = $this->load->view('oauth/login', $viewdata, true);
				$this->load->view('global/master-view', $this->data);
			}
			else
			{
				if($this->input->post('approve'))
				{
					$server->authorizeFinish(true, $user_id);
				}
				elseif($this->input->post('cancel'))
				{
					if( isset($token['callback_url']) && strlen($token['callback_url']) > 0 )
						redirect( $token['callback_url'], 'location' );
					else
						redirect( site_url('tasks'), 'location' );
				}
				else
				{
					$this->data['nosidebar'] = true;
					$this->data['content'] = $this->load->view('oauth/authorize', $viewdata, true);
					$this->load->view('global/master-view', $this->data);
				}
			}
		}
		catch(Exception $e)
		{
			$viewdata = array();
			$viewdata['message'] = $e->getMessage();
			$this->data['content'] = $this->load->view('global/message', $viewdata, true);
			$this->load->view('global/master-view', $this->data);
			return;
		}
	}
	
	/**
	*	Endpoint for getting OAuth access token
	*/	
	public function access()
	{
		$server = new OAuthServer();
		$server->accessToken();
	}
}